package com.hanserwei.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanserwei.community.entity.po.House;
import com.hanserwei.community.entity.po.MeterCategory;
import com.hanserwei.community.entity.po.MeterRecord;
import com.hanserwei.community.entity.po.Owner;
import com.hanserwei.community.entity.request.meter.MeterRecordQueryRequest;
import com.hanserwei.community.entity.request.meter.MeterRecordSaveRequest;
import com.hanserwei.community.entity.vo.HouseVO;
import com.hanserwei.community.entity.vo.MeterRecordVO;
import com.hanserwei.community.entity.vo.OwnerBriefVO;
import com.hanserwei.community.enums.ResponseCodeEnum;
import com.hanserwei.community.mapper.MeterRecordMapper;
import com.hanserwei.community.service.HouseService;
import com.hanserwei.community.service.MeterCategoryService;
import com.hanserwei.community.service.MeterRecordService;
import com.hanserwei.community.service.OwnerService;
import com.hanserwei.community.uitils.ThrowUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class MeterRecordServiceImpl extends ServiceImpl<MeterRecordMapper, MeterRecord> implements MeterRecordService {

    private final MeterCategoryService meterCategoryService;
    private final HouseService houseService;
    private final OwnerService ownerService;

    @Override
    public Page<MeterRecordVO> pageMeterRecords(MeterRecordQueryRequest request) {
        Page<MeterRecord> page = new Page<>(request.getCurrent(), request.getPageSize());
        QueryWrapper<MeterRecord> wrapper = buildQueryWrapper(request);
        Page<MeterRecord> recordPage = page(page, wrapper);
        List<MeterRecordVO> voList = convertToVOList(recordPage.getRecords());
        Page<MeterRecordVO> voPage = new Page<>(recordPage.getCurrent(), recordPage.getSize(), recordPage.getTotal());
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public MeterRecordVO getMeterRecordDetail(Integer id) {
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "抄表记录ID参数错误！");
        MeterRecord record = getById(id);
        ThrowUtils.throwIf(record == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "抄表记录不存在！");
        List<MeterRecordVO> list = convertToVOList(Collections.singletonList(record));
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public boolean createMeterRecord(MeterRecordSaveRequest request) {
        validateSaveRequest(request);
        MeterRecord record = new MeterRecord();
        BeanUtils.copyProperties(request, record);
        boolean result = save(record);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "新增失败！");
        return true;
    }

    @Override
    public boolean updateMeterRecord(Integer id, MeterRecordSaveRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "抄表记录ID参数错误！");
        validateSaveRequest(request);
        MeterRecord record = getById(id);
        ThrowUtils.throwIf(record == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "抄表记录不存在！");
        BeanUtils.copyProperties(request, record);
        record.setId(id);
        boolean result = updateById(record);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "更新失败！");
        return true;
    }

    @Override
    public QueryWrapper<MeterRecord> buildQueryWrapper(MeterRecordQueryRequest request) {
        QueryWrapper<MeterRecord> wrapper = new QueryWrapper<>();
        if (request == null) {
            return wrapper;
        }
        wrapper.eq(request.getId() != null && request.getId() > 0, "id", request.getId());
        wrapper.eq(request.getTypeId() != null && request.getTypeId() > 0, "type_id", request.getTypeId());
        wrapper.eq(request.getHouseId() != null && request.getHouseId() > 0, "house_id", request.getHouseId());
        wrapper.like(StringUtils.hasText(request.getMeter()), "meter", request.getMeter());
        wrapper.ge(request.getCurrentTimeFrom() != null, "on_time", request.getCurrentTimeFrom());
        wrapper.le(request.getCurrentTimeTo() != null, "on_time", request.getCurrentTimeTo());
        if (request.getOwnerId() != null && request.getOwnerId() > 0) {
            Owner owner = ownerService.getById(request.getOwnerId());
            if (owner == null || owner.getHouseId() == null) {
                wrapper.apply("1 = 0");
            } else {
                wrapper.eq("house_id", owner.getHouseId());
            }
        }
        wrapper.orderBy(StringUtils.hasText(request.getSortField()), !"descend".equalsIgnoreCase(request.getSortOrder()), request.getSortField());
        return wrapper;
    }

    private void validateSaveRequest(MeterRecordSaveRequest request) {
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        ThrowUtils.throwIf(request.getTypeId() == null || request.getTypeId() <= 0, ResponseCodeEnum.INVALID_PARAMETER, "抄表类型不能为空！");
        MeterCategory category = meterCategoryService.getById(request.getTypeId());
        ThrowUtils.throwIf(category == null, ResponseCodeEnum.INVALID_PARAMETER, "抄表类型不存在！");
        ThrowUtils.throwIf(request.getHouseId() == null || request.getHouseId() <= 0, ResponseCodeEnum.INVALID_PARAMETER, "关联房屋不能为空！");
        House house = houseService.getById(request.getHouseId());
        ThrowUtils.throwIf(house == null, ResponseCodeEnum.INVALID_PARAMETER, "关联房屋不存在！");
        BigDecimal previous = request.getPreviousReading();
        BigDecimal current = request.getCurrentReading();
        if (previous != null && current != null) {
            ThrowUtils.throwIf(previous.compareTo(current) > 0, ResponseCodeEnum.INVALID_PARAMETER, "本次读数不能小于上次读数！");
        }
        LocalDateTime previousTime = request.getPreviousTime();
        LocalDateTime currentTime = request.getCurrentTime();
        if (previousTime != null && currentTime != null) {
            ThrowUtils.throwIf(previousTime.isAfter(currentTime), ResponseCodeEnum.INVALID_PARAMETER, "本次抄表时间不能早于上次！");
        }
    }

    private List<MeterRecordVO> convertToVOList(List<MeterRecord> records) {
        if (CollectionUtils.isEmpty(records)) {
            return Collections.emptyList();
        }
        Set<Integer> typeIds = records.stream()
                .map(MeterRecord::getTypeId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Integer, MeterCategory> categoryMap = typeIds.isEmpty() ? Collections.emptyMap() : meterCategoryService.listByIds(typeIds).stream()
                .collect(Collectors.toMap(MeterCategory::getId, category -> category));

        Set<Integer> houseIds = records.stream()
                .map(MeterRecord::getHouseId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Integer, HouseVO> houseMap = houseIds.isEmpty() ? Collections.emptyMap() :
                houseService.getHouseVOList(houseService.listByIds(houseIds)).stream()
                        .collect(Collectors.toMap(HouseVO::getId, vo -> vo));

        Map<Integer, Owner> ownerMap = houseIds.isEmpty() ? Collections.emptyMap() : ownerService.lambdaQuery()
                .in(!houseIds.isEmpty(), Owner::getHouseId, houseIds)
                .list()
                .stream()
                .collect(Collectors.toMap(Owner::getHouseId, owner -> owner, (a, b) -> a));

        return records.stream().map(record -> {
            MeterRecordVO vo = new MeterRecordVO();
            BeanUtils.copyProperties(record, vo);
            vo.setHouseId(record.getHouseId());
            if (record.getTypeId() != null) {
                MeterCategory category = categoryMap.get(record.getTypeId());
                if (category != null) {
                    vo.setTypeName(category.getName());
                }
            }
            if (record.getHouseId() != null) {
                vo.setHouse(houseMap.get(record.getHouseId()));
                Owner owner = ownerMap.get(record.getHouseId());
                if (owner != null) {
                    vo.setOwner(toOwnerBrief(owner));
                }
            }
            return vo;
        }).toList();
    }

    private OwnerBriefVO toOwnerBrief(Owner owner) {
        if (owner == null) {
            return null;
        }
        return OwnerBriefVO.builder()
                .id(owner.getId())
                .name(owner.getUserName())
                .tel(owner.getTel())
                .houseId(owner.getHouseId())
                .build();
    }
}
